package com.gmss.crawler.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.rmi.server.ExportException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class FileUtil {

    public static void main(String[] args) throws IOException {
        System.out.println(147.0 / 8);
        System.out.println(148 % 8);
        System.out.println(JSON.toJSONString(readFileLines("/crawlerUrlFile/cas.txt", ";")));
    }

    /**
     * @param resourcesfilePath resources下的文件路径
     * @param regex             分隔符
     * @return
     * @throws IOException
     */
    public static Map<String, String> readFileLines(String resourcesfilePath, String regex) throws IOException {
//        Resource resource = new ClassPathResource("/crawlerUrlFile/cas.txt");
        Resource resource = new ClassPathResource(resourcesfilePath);
//        System.out.println(resource.getFile().getAbsolutePath());
        String filePath = resource.getFile().getAbsolutePath();
        File file = new File(filePath);
        if (!file.exists())
            throw new ExportException("文件不存在！");
        List<String> lines = FileUtils.readLines(file, StandardCharsets.UTF_8);
        Map<String, String> mapUrl = new LinkedHashMap<>();
        for (int i = 0; i < lines.size(); i++) {
            if (StringUtils.isBlank(lines.get(i)))
                continue;
            String[] arrs = lines.get(i).split(regex);
            if (StringUtils.isNoneBlank(lines.get(i)) && arrs.length > 1) {
                String key = arrs[0];
                String value = arrs[1];
                if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value))
                    mapUrl.put(key, value);
            } else {
                mapUrl.put(String.valueOf(i), lines.get(i));
            }
        }
        return mapUrl;
    }

    public static List<String> readFileLines(String resourcesfilePath) throws IOException {
//        Resource resource = new ClassPathResource("/crawlerUrlFile/cas.txt");
        Resource resource = new ClassPathResource(resourcesfilePath);
//        System.out.println(resource.getFile().getAbsolutePath());
        String filePath = resource.getFile().getAbsolutePath();
        File file = new File(filePath);
        if (!file.exists())
            throw new ExportException("文件不存在！");
        List<String> lines = FileUtils.readLines(file, StandardCharsets.UTF_8);
        return lines;
    }
}
